package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 聊天室的客户端
 */
public class Server {
    private ServerSocket ServerSocket;

    public Server() {
        try {
            System.out.println("正在启动服务端");
            ServerSocket = new ServerSocket(8088);
            System.out.println("服务端启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待接收客户端");
                Socket socket = ServerSocket.accept();
                System.out.println("一个客户端已连接");
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                String message;
                while ((message = br.readLine()) != null) {
                    System.out.println(message);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        //main方法时静态方法，不能访问普通方法
        //调用构造器初始化数据
        Server server = new Server();
        server.start();
    }
}
